package no.kolstad.movies.webapp.controller;

import org.apache.commons.lang.StringUtils;
import no.kolstad.movies.service.GenericManager;
import no.kolstad.movies.model.Loaner;
import no.kolstad.movies.webapp.controller.BaseFormController;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class LoanerFormController extends BaseFormController {
    private GenericManager<Loaner, Long> loanerManager = null;

    public void setLoanerManager(GenericManager<Loaner, Long> loanerManager) {
        this.loanerManager = loanerManager;
    }

    public LoanerFormController() {
        setCommandClass(Loaner.class);
        setCommandName("loaner");
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return loanerManager.get(new Long(id));
        }

        return new Loaner();
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        log.debug("entering 'onSubmit' method...");

        Loaner loaner = (Loaner) command;
        boolean isNew = (loaner.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            loanerManager.remove(loaner.getId());
            saveMessage(request, getText("loaner.deleted", locale));
        } else {
            loanerManager.save(loaner);
            String key = (isNew) ? "loaner.added" : "loaner.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:loanerform.html?id=" + loaner.getId();
            }
        }

        return new ModelAndView(success);
    }
}
